package com.kye.express.business.deposit.activity;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.net.NetworkInfo;
import android.os.Bundle;

import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.base.utils.NetworkMonitorUtils;
import com.kye.express.R;
import com.kye.express.business.base.BaseToolbarActivity;
import com.kye.express.business.deposit.adapter.DepositViewPagerAdapter;
import com.kye.express.business.deposit.presenter.DepositContract;
import com.kye.express.business.deposit_recharge.offline.RechargeOfflineActivity;
import com.kye.express.business.deposit_recharge.online.RechargeOnlineActivity;
import com.kye.express.business.login.LoginActivity;
import com.kye.express.databinding.ActivityDepositBinding;
import com.kye.express.utils.ActivityManager;
import com.kye.express.view.ToastManager;
import com.kye.model.SharedPreferencesConfig;
import com.kye.model.SharedPreferencesManager;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.deposit.ResultIsNeedTicketBean;
import com.kye.model.bean.deposit.ResultQueryReserveBalanceBean;
import com.kye.model.bean.user.User;
import com.kye.model.constant.Constants;

/**
 * 预存运费 Activity
 * <p>
 * Created by SkyYu on 2018/1/16
 */
public class DepositActivity extends BaseToolbarActivity implements DepositContract.DepositView {

    private final static String TAG = DepositActivity.class.getSimpleName();

    private ActivityDepositBinding mBinding;
    private DepositContract.DepositPresenter mPresenter;
    private ResultIsNeedTicketBean mIsNeedTicketBean;

    public static void startActivity() {
        ActivityManager.getInstance().getCurrentActivity().startActivity(new Intent(ActivityManager.getInstance().getCurrentActivity(), DepositActivity.class));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initEvent();
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mPresenter) mPresenter.unbind();
        SharedPreferencesManager.remove(SharedPreferencesConfig.KEY_RECHARGE_OFFLINE_USERNAME);
        SharedPreferencesManager.remove(SharedPreferencesConfig.KEY_RECHARGE_OFFLINE_BANKNAME);
        SharedPreferencesManager.remove(SharedPreferencesConfig.KEY_RECHARGE_OFFLINE_ACCOUNT);
    }

    private void initView() {
        initDataBinding();
        initTitle();
    }

    private void initDataBinding() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_deposit);
    }

    private void initTitle() {
        setUpToolbar(mBinding.toolbarDeposit);
        setTitle(getString(R.string.deposit_title));
    }

    private void initData() {
        initPresenter();
        initAdapter();
    }

    private void initPresenter() {
        mPresenter = new DepositContract.DepositPresenter();
        mPresenter.bind(this);
    }

    private void initAdapter() {
        mBinding.viewpagerDeposit.setAdapter(new DepositViewPagerAdapter(getSupportFragmentManager()));
        mBinding.viewpagerDeposit.setOffscreenPageLimit(getResources().getStringArray(R.array.deposit_bar_titles).length);
        mBinding.slidingtablayoutDeposit.setViewPager(mBinding.viewpagerDeposit, getResources().getStringArray(R.array.deposit_bar_titles));
        mBinding.viewpagerDeposit.setCurrentItem(0);
    }

    private void initEvent() {
        RxView.clicks(mBinding.buttonDepositRecharge)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe((Object) -> {
                    if (null != mIsNeedTicketBean) {
                        if (mIsNeedTicketBean.isIsVoucher()) {
                            // 需要上传凭证（跳转线下充值页）
                            SharedPreferencesManager.commit(SharedPreferencesConfig.KEY_RECHARGE_OFFLINE_USERNAME, mIsNeedTicketBean.getUserName());
                            SharedPreferencesManager.commit(SharedPreferencesConfig.KEY_RECHARGE_OFFLINE_BANKNAME, mIsNeedTicketBean.getBankName());
                            SharedPreferencesManager.commit(SharedPreferencesConfig.KEY_RECHARGE_OFFLINE_ACCOUNT, mIsNeedTicketBean.getAccount());
                            RechargeOfflineActivity.startActivity();
                        } else {
                            RechargeOnlineActivity.startActivity();
                        }
                    } else {
                        Logger.d(TAG + " - initEvent - mIsNeedTicketBean is null");
                    }
                });
    }

    @Override
    public void onLoadUser(User user) {
        isLogin(user);
    }

    @Override
    public void onLoadBalanceSuccess(OpenApiResult<ResultQueryReserveBalanceBean> result) {
        if (result != null) {
            if (result.getCode() == Constants.ResponseCode_SUCCESS) {
                if (result.getData() != null) {
                    mBinding.textviewDepositBalance.setText(String.format(getString(R.string.depositfreight_balance_symbol), result.getData().getCurrentMoney()));
                } else {
                    Logger.d(TAG + " - onLoadBalance - result.data is null");
                }
            } else {
                ToastManager.show(this, result.getMsg());
            }
        } else {
            Logger.d(TAG + " - onLoadBalance - result is null");
        }
    }

    @Override
    public void onLoadBalanceApiError(OpenApiResult<ResultQueryReserveBalanceBean> result,
                                      int code, String msg) {
        ToastManager.show(this, msg);
        Logger.d(TAG + " - onLoadBalanceApiError - result:" + result + ",code:" + code + ",msg:" + msg);
    }

    @Override
    public void onLoadBalanceOtherError(Throwable e) {
        ToastManager.show(this, getString(R.string.common_net_error));
        Logger.d(TAG + " - onOtherError : " + e.getMessage());
        e.printStackTrace();
    }

    @Override
    public void onLoadIsNeedTicketSuccess(OpenApiResult<ResultIsNeedTicketBean> result) {
        if (result != null) {
            if (result.getCode() == Constants.ResponseCode_SUCCESS) {
                if (result.getData() != null) {
                    mIsNeedTicketBean = result.getData();
                } else {
                    Logger.d(TAG + " - onLoadIsNeedTicket - result.data is null");
                }
            } else {
                ToastManager.show(this, result.getMsg());
            }
        } else {
            Logger.d(TAG + " - onLoadIsNeedTicket - result is null");
        }
    }

    @Override
    public void onLoadIsNeedTicketApiError(OpenApiResult<ResultIsNeedTicketBean> result,
                                           int code, String msg) {
        ToastManager.show(this, msg);
        Logger.d(TAG + " - onLoadIsNeedTicketApiError - result:" + result + ",code:" + code + ",msg:" + msg);
    }

    @Override
    public void onLoadIsNeedTicketOtherError(Throwable e) {
        ToastManager.show(this, getString(R.string.common_net_error));
        Logger.d(TAG + " - onLoadIsNeedTicketOtherError : " + e.getMessage());
        e.printStackTrace();
    }

    private void isLogin(User user) {
        if (user == null || !user.isLogin()) {
            ToastManager.show(this, getString(R.string.common_login));
            LoginActivity.startActivity(this);
        } else {
            request(user);
        }
    }

    private void request(User user) {
        NetworkMonitorUtils.networkObservable(this)
                .compose(this.bindToLifecycleDestroy())
                .map((connectivity) -> {
                    NetworkInfo.State state = connectivity.getState();
                    switch (state) {
                        case CONNECTED:
                        case CONNECTING:
                            return true;
                        case DISCONNECTED:
                        case DISCONNECTING:
                            return false;
                        default:
                            return false;
                    }
                })
                .subscribe((Boolean) -> {
                    if (Boolean) {
                        mPresenter.requestToQueryReserveBalance(user.getPhone(), user.getCustomCode());
                        mPresenter.requestToIsNeedTicket(user.getPhone(), user.getLastAddress().get(0).getCompanyCode());
                    } else {
                        ToastManager.show(this, getString(R.string.common_net_error));
                    }
                });
    }
}